package com.yanjue.service.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yanjue.common.constant.RedisConstants;
import com.yanjue.common.entity.UserLikeSee;
import com.yanjue.common.redisKey.RedisAccountKey;
import com.yanjue.common.redisKey.RedisExpire;
import com.yanjue.common.redisKey.RedisService;
import com.yanjue.mapper.UserLikeSeeMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 用户喜欢看点击任务
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class LikeSeeClickTask implements Runnable{
    private RedisService redisService;
    private String bookId;
    private Integer value;
    private UserLikeSeeMapper likeSeeMapper;


    @Override
    public void run() {
        //用户点击喜欢，，对应的书要增加或减少喜欢数
        //1.如果该书的喜欢数key存在，那么就进行加减
        String key = RedisAccountKey.ACCOUNT_CENTER_BOOK_LIKES_COUNT;
        if (this.redisService.hashHasKey(key, this.bookId)){
            int val = 1;
            if (value <= 0){
                val -= 2;
            }
            this.redisService.hashIncrement(key,this.bookId,val);
        }else {
            //2.如果不存在，，读数据库(按逻辑数据库一定存在)
            // 少数据库字段，
            LambdaQueryWrapper<UserLikeSee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserLikeSee::getBookId,bookId);
            Long count = likeSeeMapper.selectCount(queryWrapper);

            //count = value > 0 ? ++count : --count;
            if (value > 0 ){
                count++;
            }else {
                count--;
            }
            //3.更新缓存
            this.redisService.setHashValExpire(key,this.bookId,count, RedisExpire.MONTH);
        }
    }
}
